package cn.ven.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
@EnableAuthorizationServer
public class QqAuth2ServerConfig extends
        AuthorizationServerConfigurerAdapter {
    @Autowired
    AuthenticationManager authenticationManagerBean;

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        System.out.println("checkTokenAccess(\"permitAll()\")");
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()") //allow check token
                .allowFormAuthenticationForClients();
    }

    // 配置哪些 client_id client_secret
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        System.out.println("configure(ClientDetailsServiceConfigurer clients)");
        clients.inMemory()
                .withClient("soblog").secret(passwordEncoder.encode("1433223"))
                .authorizedGrantTypes("password", "authorization_code",
                        "client_credentials", "implicit", "refresh_token")
                .scopes("all").accessTokenValiditySeconds(60*60*180);

    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        System.out.println("configure(AuthorizationServerEndpointsConfigurer endpoints)");
        endpoints.authenticationManager(authenticationManagerBean)
                .userDetailsService(userDetailsService);
    }
}
